package net.apexes.commons.lang;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author <a href=mailto:hedyn@foxmail.com>HeDYn</a>
 */
public class AsyncExecutorDemo {

    private static final Logger LOG = LoggerFactory.getLogger(AsyncExecutorDemo.class);

    public static void main(String[] args) throws Exception {
        AsyncExecutor.Worker<Integer> worker = new AsyncExecutor.Worker<Integer>() {
            @Override
            public void execute(Integer data) {
                LOG.info("execute {} ...", data);
                try {
                    Thread.sleep(500);
                } catch (Exception ex) {
                    LOG.error("await error.", ex);
                }
            }
        };
        AsyncExecutor.ErrorMonitor errorMonitor = new AsyncExecutor.ErrorMonitor() {
            @Override
            public void onError(Exception exception) {
                LOG.error("onError", exception);
            }
        };

        AsyncExecutor<Integer> executor = AsyncExecutor.builder()
                .queueCapacity(100)
                .parallelism(4)
                .errorMonitor(errorMonitor)
                .build(worker);
        executor.start();
        for (int i = 0; i < 30; i++) {
            LOG.info("offer : {}", i);
            executor.offer(i);
            LOG.info("queueSize={}", executor.getQueueSize());
        }

        // 本例通过判断队列是否为空来关闭处理器，实际应用中应该在程序关闭时调用 close() 方法
        while (true) {
            LOG.info("queueSize={}", executor.getQueueSize());
            if (executor.getQueueSize() == 0) {
                Thread.sleep(1000);
                break;
            }
            Thread.sleep(1000);
        }
        executor.close();
    }
}
